<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@page import="org.springframework.web.context.WebApplicationContext"%>
<%@page import="org.springframework.web.context.support.WebApplicationContextUtils"%>
<%@page import="db.PurreqDAO"%>
<%@page import="db.PurmatDAO"%>
<%@page import="db.Purmat"%>
<%@page import="db.TmppurDAO"%>
<%@page import="db.Tmppur"%>
<%@page import="java.text.SimpleDateFormat"%>
<%@page import="org.json.JSONObject"%>
<%@page import="db.Purreq"%>
<%@page import="db.User"%>
<%@page import="db.Msg"%>
<%@page import="db.MsgDAO"%>
<%@page import="db.UserDAO"%>
<%@ include file="/jsp/common/utility/logined.jsp" %>
<%
	WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
	PurreqDAO purreqDao = (PurreqDAO)ctx.getBean("PurreqDAO");
	PurmatDAO purmatDao = (PurmatDAO)ctx.getBean("PurmatDAO");
	TmppurDAO tmppurDao = (TmppurDAO)ctx.getBean("TmppurDAO");
	
	String purreqIdStr = request.getParameter("purreqId");
	int purreqId = 0;
	try{
		purreqId = Integer.parseInt(purreqIdStr);
	}catch(Exception e){
		purreqId = 0;
	}
	
	int tid = (Integer)session.getAttribute("tid");
	int uid = (Integer)session.getAttribute("id");
	Date date = new Date();
	
	Tmppur tmppur = new Tmppur();
	tmppur.setDate(date);
	tmppur.setPurreqId(purreqId);
	tmppur.setState(1);
	tmppur.setTmpUserid(uid);
	tmppur.setTeamId(tid);
	tmppurDao.save(tmppur);
	
	tmppur.setTmpCode("L" + tmppur.getId());
	tmppurDao.attachDirty(tmppur);
	
	submitMsg(9,7,"提交临时采购订单!",session);
	
	String[] ids = request.getParameterValues("ids");
	String[] nums = request.getParameterValues("nums");
	
	if(ids != null && ids.length > 0)
	for(int i=0;i<ids.length;i++){
		int purmatId = Integer.parseInt(ids[i]);
		Purmat purmat = purmatDao.findById(purmatId);
		purmat.setState(3);
		purmat.setBuyNum(Integer.parseInt(nums[i]));
		purmat.setWareNum(Integer.parseInt(nums[i])); //在此处写入跟最终采购数量相同的数量，用于在入库的时候多次入库。这个值可以进行减少。如果减少为0则这个物资完全入库。如果一个临时订单的所有物资这个数都为零则这个临时订单已经入库完毕应该修改临时订单状态为2。
		purmat.setTmppurId(tmppur.getId());
		purmatDao.attachDirty(purmat);
	}
	
	JSONObject json = new JSONObject();
	List purmats = purmatDao.findByPurreqIdAndState(new Object[]{purreqId, 1});
	json.put("code",tmppur.getTmpCode());
	if(purmats != null && purmats.size() > 0){
		json.put("remain",purmats.size());
	}else{
		Purreq purreq = purreqDao.findById(purreqId);
		purreq.setState(5);
		purreqDao.attachDirty(purreq);
		
		json.put("remain",0);
	}
	
	out.print(json.toString());
%>